package com.ccx.coachsite.ui.own;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.ccx.coachsite.CoachSiteMainActivity;
import com.ccx.coachsite.bus.Account;
import com.ccx.coachsite.bus.AccountMgr;
import com.ccx.coachsite.bus.MessageInfo;
import com.ccx.coachsite.bus.OwerShareInfo;
import com.ccx.coachsite.bus.ShareInfo;
import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.bus.SoftInfo;
import com.ccx.coachsite.bus.UserInfo;
import com.ccx.coachsite.http.BaseResp;
import com.ccx.coachsite.http.HttpRequest;
import com.ccx.coachsite.http.UrlConfig;
import com.ccx.coachsite.util.Log;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;

public class OwerProvider {
	private int errorCode = 200;
	private static OwerProvider instance;

	public static OwerProvider getInstance() {
		if (instance == null)
			instance = new OwerProvider();
		return instance;
	}

	public int getLastErrorCode() {
		return errorCode;
	}
	
	public void loginOut(Context context)
	{
		SharedPreferencesUtil.setValue(context,
				SharedKey.Shared_UserId_Key, "");
		SharedPreferencesUtil.setBoolean(context,
				SharedKey.Shared_Is_Expert, false);
		SharedPreferencesUtil.setValue(context,
				SharedKey.Shared_Mobile_Key, "");
		SharedPreferencesUtil.setValue(context,
				SharedKey.Shared_Password_Key, "");
		SharedPreferencesUtil.setValue(context,
				SharedKey.Shared_Login_Type, "");
		SharedPreferencesUtil.setValue(context,
				SharedKey.Shared_Weibo_Id, "");
		SharedPreferencesUtil.setValue(context,
				SharedKey.Shared_Weibo_Name, "");
		
		SharedPreferencesUtil.setValue(context,
				SharedKey.Custom_Message_Count, "");
		
		Account ac = new Account();
		AccountMgr.saveAccountInfo(context, ac);
		CoachSiteMainActivity activity = (CoachSiteMainActivity)context;
		activity.showChoosedView(CoachSiteMainActivity.APP_VIEW);
	}

	protected List<UserInfo> getFriendList(Context context) {
		List<UserInfo> mApp = new ArrayList<UserInfo>();
		try {
			String mobile = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_Mobile_Key, "");
			String firendUrl = UrlConfig
					.getUrlByKey(UrlConfig.OwerFriendUrlKey);
			firendUrl += "?phone=" + mobile;
			BaseResp br = HttpRequest.DoHttpRequest(firendUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONArray respsonList = jsonObject.getJSONArray("response");
				for (int i = 0; i < respsonList.length(); i++) {
					JSONObject obj = respsonList.getJSONObject(i);
					UserInfo info = new UserInfo();
					info.setId(obj.getInt("id"));
					info.setUsername(obj.getString("name"));
					info.setIcon(obj.getString("icon"));
					mApp.add(info);
				}
			}
		} catch (Exception e) {
			mApp = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mApp;
	}

	public List<String> getInviteLog(Context context) {
		List<String> mApp = new ArrayList<String>();
		try {
			String mobile = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_Mobile_Key, "");
			String baseUrl = UrlConfig
					.getUrlByKey(UrlConfig.OwerAddFriendLogUrlKey);
			baseUrl = baseUrl + "?phone＝" + mobile;
			BaseResp br = HttpRequest.DoHttpRequest(baseUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());

				JSONArray respsonList = jsonObject.getJSONArray("response");
				if (respsonList != null && respsonList.length() > 0) {
					for (int i = 0; i < respsonList.length(); i++) {
						JSONObject obj = respsonList.getJSONObject(i);
						mApp.add(obj.getString("invitedRrecord"));
					}
				}
			}
		} catch (Exception e) {
			mApp = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mApp;
	}

	public List<SoftInfo> getCollectList(Context context) {
		List<SoftInfo> mApp = new ArrayList<SoftInfo>();
		try {
			String userId = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_UserId_Key, "");
			String baseUrl = UrlConfig.getUrlByKey(UrlConfig.OwerCollectUrlKey);
			baseUrl = baseUrl + "?userId=" + userId;
			BaseResp br = HttpRequest.DoHttpRequest(baseUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONObject respsonObject = jsonObject.getJSONObject("response");
				if(respsonObject == null)
					return mApp;
				
				JSONArray appList = respsonObject.getJSONArray("appList");
				if(appList != null)
				{
					for (int i = 0; i < appList.length(); i++) {
						JSONObject obj = appList.getJSONObject(i);
						SoftInfo info = new SoftInfo();
						info.setId(obj.getInt("id"));
						info.setName(obj.getString("name"));
						info.setIcon(obj.getString("iconUrl"));
						//info.setStar(obj.getInt("star"));
						mApp.add(info);
					}
				}
				
				JSONArray tutorialList = respsonObject.getJSONArray("tutorialList");
				if(tutorialList != null)
				{
					for (int i = 0; i < tutorialList.length(); i++) {
						JSONObject obj = tutorialList.getJSONObject(i);
						SoftInfo info = new SoftInfo();
						info.setId(obj.getInt("id"));
						info.setName(obj.getString("name"));
						info.setIcon(obj.getString("tutorialUrl"));
						info.setSoftType(1);
						//info.setStar(obj.getInt("star"));
						mApp.add(info);
					}
				}
				
			}
		} catch (Exception e) {
			mApp = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mApp;
	}

	public List<MessageInfo> getMessageList(Context context) {
		List<MessageInfo> mApp = new ArrayList<MessageInfo>();
		try {
			String userId = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_UserId_Key, "");
			if(StringUtil.isEmpty(userId))
				return mApp;
			
			String mobile = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_Mobile_Key, "");
			String baseUrl = UrlConfig.getUrlByKey(UrlConfig.OwerMessageUrlKey);
			baseUrl = baseUrl + "?mobile=" + mobile+UrlConfig.PageString;
			BaseResp br = HttpRequest.DoHttpRequest(baseUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONObject responObj = jsonObject.getJSONObject("response");
				if(responObj != null)
				{
					JSONArray respsonList = responObj.getJSONArray("list");
					for (int i = 0; i < respsonList.length(); i++) {
						JSONObject obj = respsonList.getJSONObject(i);
						MessageInfo info = new MessageInfo();
						info.setId(obj.getInt("id"));
						info.setTitle(obj.getString("title"));
						info.setCreator(obj.getString("nickName"));
						info.setTimes(obj.getString("createTime"));
						if(!obj.isNull("status"))
							info.setIsReaded(obj.getInt("status"));
						mApp.add(info);
					}
				}
			}
		} catch (Exception e) {
			mApp = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mApp;
	}

	public boolean getMessageDetail(Context context, MessageInfo mMessageInfo) {
		boolean result = false;
		try {
			String baseUrl = UrlConfig
					.getUrlByKey(UrlConfig.OwerMessageDetailUrlKey);
			
			String mobile = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_Mobile_Key, "");
			baseUrl = baseUrl + "?id=" + mMessageInfo.getId() + "&mobile=" + mobile;
			BaseResp br = HttpRequest.DoHttpRequest(baseUrl);

			if (br.isSuccess()) {
				JSONObject jsonObject = new JSONObject(br.getHttpResult());
				JSONObject respsonList = jsonObject.getJSONObject("response");
				mMessageInfo.setContent(respsonList.getString("content"));
				result = true;
			}

		} catch (Exception e) {
			result = false;
			Log.e(e.getMessage(), e);
		} finally {
		}
		return result;
	}
	
	private String GetDateTime(String Time)
	{
		String createTime = Time;
		if(createTime != null)
		{
			if(createTime.length() > 10)
				createTime = createTime.substring(0, 10);
		}
		return createTime;
	}
	
	private void addListItem(List<String> lst, String item)
	{
		if(lst.indexOf(item) < 0)
			lst.add(item);
	}

	public OwerShareInfo getShareList(Context context) {
		OwerShareInfo mOwerShareInfo = null;
		try {
			String userId = SharedPreferencesUtil.getValue(context,
					SharedKey.Shared_UserId_Key, "");
			String baseUrl = UrlConfig.getUrlByKey(UrlConfig.OwerShareUrlKey);
			baseUrl = baseUrl + "?userId=" + userId;
			BaseResp br = HttpRequest.DoHttpRequest(baseUrl);

			if (br.isSuccess()) {
				mOwerShareInfo = new OwerShareInfo();
				JSONObject root = new JSONObject(br.getHttpResult());
				int collectCount = 0;
				JSONObject respsonObject = root.getJSONObject("response");
				if(!respsonObject.isNull("collectNum"))
					mOwerShareInfo.setFavCount(respsonObject.getInt("collectNum"));
				if(!respsonObject.isNull("shareAppNum"))
					mOwerShareInfo.setShareCount(respsonObject
						.getInt("shareAppNum"));
				if(!respsonObject.isNull("sharefriendNum"))
					mOwerShareInfo.setShareFriendCount(respsonObject
						.getInt("sharefriendNum"));
				Account acc = AccountMgr.readAccountInfo(context);
				mOwerShareInfo.setIcon(acc.getOwerIcon());
				collectCount = acc.getOwerCollectCount();
				mOwerShareInfo.setFavCount(collectCount);
				
				List<SoftInfo> mTutorialList = new ArrayList<SoftInfo>();
				mOwerShareInfo.setShareTurList(mTutorialList);
				List<String> lstNames = new ArrayList<String>();
				List<String> lstApps = new ArrayList<String>();
				JSONArray tutorialList = respsonObject.getJSONArray("tutorialList");
				if (tutorialList != null) {
					for (int i = 0; i < tutorialList.length(); i++) {
						JSONObject shareObject = tutorialList.getJSONObject(i);
						SoftInfo info = new SoftInfo();
						info.setId(shareObject.getInt("id"));
						info.setName(shareObject.getString("name"));
						info.setIcon(shareObject.getString("tutorialUrl"));
						info.setUserName(shareObject.getString("sharedUser"));
						info.setTime(shareObject.getString("createdTime"));
						mTutorialList.add(info);
						
						addListItem(lstNames, info.getUserName());
						addListItem(lstApps, info.getId()+"");
					}
				}
				
				List<ShareInfo> mApp = new ArrayList<ShareInfo>();
				mOwerShareInfo.setShareList(mApp);
				
				JSONArray shareList = respsonObject.getJSONArray("appList");
				if (shareList != null) {
					for (int i = 0; i < shareList.length(); i++) {
						JSONObject shareObject = shareList.getJSONObject(i);
						
						String createTime = shareObject.getString("createdTime");
						createTime = GetDateTime(createTime);
						
						String sharedUser = shareObject.getString("sharedUser");
						ShareInfo sinfo = null;
						for(int j =0; j<mApp.size(); j++)
						{
							ShareInfo tmp = mApp.get(j);
							String TmpCreateTime = GetDateTime(tmp.getShareTime());
							
							if(TmpCreateTime.equals(createTime) && tmp.getShareUser().equals(sharedUser))
							{
								sinfo = tmp;
								break;
							}
						}
						
						if(sinfo == null)
						{
							sinfo = new ShareInfo();
							sinfo.setShareTime(createTime);
							sinfo.setShareUser(sharedUser);
							mApp.add(sinfo);
						}
						
						List<SoftInfo> appList = sinfo.getShareList();
						if(appList == null)
						{
							appList = new ArrayList<SoftInfo>();
							sinfo.setShareList(appList);
						}
						
						SoftInfo info = new SoftInfo();
						info.setId(shareObject.getInt("id"));
						info.setName(shareObject.getString("name"));
						info.setIcon(shareObject.getString("iconUrl"));
						info.setUserName(shareObject.getString("sharedUser"));
						appList.add(info);
						
						addListItem(lstNames, info.getUserName());
						addListItem(lstApps, info.getId()+"");
						/*
						JSONArray softList = shareObject.getJSONArray("app");
						List<SoftInfo> appList = new ArrayList<SoftInfo>();
						sinfo.setShareList(appList);

						if (shareList != null) {

							for (int j = 0; j < softList.length(); j++) {
								JSONObject softObject = softList
										.getJSONObject(j);
								SoftInfo info = new SoftInfo();
								info.setId(softObject.getInt("appId"));
								info.setName(softObject.getString("appName"));
								info.setIcon(softObject.getString("appImgUrl"));
								appList.add(info);
							}
						}

						mApp.add(sinfo);
						*/
					}
				}
				mOwerShareInfo.setShareCount(lstApps.size());
				mOwerShareInfo.setShareFriendCount(lstNames.size());
			}
		} catch (Exception e) {
			mOwerShareInfo = null;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return mOwerShareInfo;
	}

	public boolean getFriendDetail(Context context, UserInfo uinfo) {
		boolean result = false;
		try {
			String baseUrl = UrlConfig
					.getUrlByKey(UrlConfig.OwerFriendDetailUrlKey);
			baseUrl = baseUrl + "?id=" + uinfo.getId();
			BaseResp br = HttpRequest.DoHttpRequest(baseUrl);

			if (br.isSuccess()) {
				JSONObject root = new JSONObject(br.getHttpResult());
				JSONObject respsonObject = root.getJSONObject("response");
				uinfo.setMobile(respsonObject.getString("tianyiPhone"));
				uinfo.setRole(respsonObject.getString("roleName"));
				uinfo.setStar(respsonObject.getInt("star"));
				uinfo.setCollectCount(respsonObject.getInt("collectNum"));
				uinfo.setFriendCount(respsonObject.getInt("friendNum"));
				List<SoftInfo> mApp = new ArrayList<SoftInfo>();

				JSONArray softList = respsonObject.getJSONArray("app");
				if (softList != null) {
					for (int i = 0; i < softList.length(); i++) {
						JSONObject softObject = softList.getJSONObject(i);
						SoftInfo sinfo = new SoftInfo();
						sinfo.setId(softObject.getInt("appId"));
						sinfo.setName(softObject.getString("appName"));
						sinfo.setIcon(softObject.getString("appImgUrl"));
						mApp.add(sinfo);
					}
					uinfo.setSofts(mApp);
				}
				result = true;
			}

		} catch (Exception e) {
			result = false;
			Log.e(e.getMessage(), e);
		} finally {
		}

		return result;
	}
}
